package com.example.test02;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;

import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Patterns;
import android.widget.Button;
import android.widget.EditText;

import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class RegisterActivity extends AppCompatActivity {

    private EditText editTextPhone;
    private EditText editTextUsername;
    private EditText editTextPassword;
    private EditText editTextRePassword;

    // 检测 WiFi 权限
//    private final ActivityResultLauncher<String[]> requestPermissionsLauncher =
//            registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), result -> {
//                boolean allPermissionsGranted = true;
//                for (Boolean isGranted : result.values()) {
//                    if (!isGranted) {
//                        allPermissionsGranted = false;
//                        break;
//                    }
//                }
//                if (allPermissionsGranted) {
//                    // 所有权限已授予，继续正常逻辑
//                    Toast.makeText(RegisterActivity.this, "所有权限已授予", Toast.LENGTH_SHORT).show();
//                    checkWifiConnectionAndBroadcast();
//                } else {
//                    // 权限被拒绝，提示用户
//                    showPermissionDeniedDialog_wifi();
//                }
//            });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        editTextPhone = findViewById(R.id.editTextPhone);
        editTextUsername = findViewById(R.id.editTextUsername);
        editTextPassword = findViewById(R.id.editTextPassword);
        editTextRePassword = findViewById(R.id.editTextRePassword);

        Button registerButton = findViewById(R.id.registerButton);
        registerButton.setOnClickListener(v -> attemptRegister());

        TextView backToLogin = findViewById(R.id.backToLogin);
        backToLogin.setOnClickListener(v -> {
            // 关闭当前注册页面，返回登录页面
            finish();
        });

        // 在页面加载时检查 WiFi 权限并尝试广播 WiFi 信息
        //checkAndRequestWifiPermissions();
    }

    private void attemptRegister() {
        String phone = editTextPhone.getText().toString().trim();
        String username = editTextUsername.getText().toString().trim();
        String password = editTextPassword.getText().toString().trim();
        String rePassword = editTextRePassword.getText().toString().trim();

        // 简单验证
        if (phone.isEmpty() || username.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "所有字段不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!Patterns.PHONE.matcher(phone).matches()) {
            Toast.makeText(this, "请输入有效的手机号码", Toast.LENGTH_SHORT).show();
            editTextPhone.setText("");
            return;
        }

        if (!password.equals(rePassword)) {
            Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
            editTextPassword.setText("");
            editTextRePassword.setText("");
            return;
        }

        register(phone, username, password);
    }

    private void register(String phone, String userName, String password) {
        OkHttpClient client = new OkHttpClient();

        FormBody body = new FormBody.Builder()
                .add("phone", phone)
                .add("userName", userName)
                .add("password", password)
                .build();

        Request request = new Request.Builder()
                .url("http://120.26.59.7:17321/api/user/register") // 替换为您的服务器地址
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() ->
                        Toast.makeText(RegisterActivity.this, "注册请求失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseData = response.body().string();
                try {
                    JSONObject jsonResponse = new JSONObject(responseData);
                    int code = jsonResponse.getInt("code");
                    String message = jsonResponse.getString("message");

                    runOnUiThread(() -> {
                        if (code == 0) {
                            Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                            // 注册成功后返回登录界面
                            new Handler(Looper.getMainLooper()).postDelayed(() -> finish(), 1000);
                        } else {
                            Toast.makeText(RegisterActivity.this, "注册失败: " + message, Toast.LENGTH_SHORT).show();
                            editTextPhone.setText("");
                            editTextUsername.setText("");
                            editTextPassword.setText("");
                            editTextRePassword.setText("");
                        }
                    });
                } catch (JSONException e) {
                    runOnUiThread(() ->
                            Toast.makeText(RegisterActivity.this, "响应解析失败", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }

//    // 检测 WiFi 权限
//    private void checkAndRequestWifiPermissions() {
//        // 需要请求的权限
//        String[] requiredPermissions = {
//                Manifest.permission.ACCESS_WIFI_STATE,
//                Manifest.permission.CHANGE_WIFI_STATE,
//                Manifest.permission.ACCESS_FINE_LOCATION,
//                Manifest.permission.ACCESS_COARSE_LOCATION
//        };
//
//        // 检查是否已授予所有权限
//        boolean allPermissionsGranted = true;
//        for (String permission : requiredPermissions) {
//            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
//                allPermissionsGranted = false;
//                break;
//            }
//        }
//
//        if (allPermissionsGranted) {
//            // 所有权限已授予，直接检查 WiFi 连接并广播
//            checkWifiConnectionAndBroadcast();
//        } else {
//            // 请求权限
//            requestPermissionsLauncher.launch(requiredPermissions);
//        }
//    }
//
//    // 显示权限拒绝对话框
//    private void showPermissionDeniedDialog_wifi() {
//        new AlertDialog.Builder(this)
//                .setTitle("需要权限")
//                .setMessage("需要 WiFi 和位置权限来继续操作")
//                .setPositiveButton("设置", (dialog, which) -> openAppSettings_wifi())
//                .setNegativeButton("取消", null)
//                .show();
//    }
//
//    // 打开应用设置页面
//    private void openAppSettings_wifi() {
//        Intent intent = new Intent();
//        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
//        Uri uri = Uri.fromParts("package", getPackageName(), null);
//        intent.setData(uri);
//        startActivity(intent);
//    }

//    // 检测 WiFi 连接并广播 WiFi 信息
//    private void checkWifiConnectionAndBroadcast() {
//        String ssid = getCurrentWifiSsid();
//        String password = getCurrentWifiPassword();
//        if (!ssid.isEmpty() && !password.isEmpty()) {
//            broadcastWifiInfo(ssid, password);
//        } else {
//            Toast.makeText(this, "无法获取 WiFi 信息", Toast.LENGTH_SHORT).show();
//        }
//    }
//
//    // 获取当前 WiFi 的 SSID
//    private String getCurrentWifiSsid() {
//        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
//        if (wifiInfo.getNetworkId() == -1) {
//            // 设备未连接到 WiFi
//            Toast.makeText(this, "设备未连接到 WiFi", Toast.LENGTH_SHORT).show();
//            return "";
//        }
//        String ssid = wifiInfo.getSSID().replace("\"", ""); // 去除双引号
//        return ssid;
//    }
//
//    // 获取当前 WiFi 的密码
//    private String getCurrentWifiPassword() {
//        SharedPreferences sharedPreferences = getSharedPreferences("WifiPrefs", Context.MODE_PRIVATE);
//        String password = sharedPreferences.getString("wifi_password", "");
//        if (password.isEmpty()) {
//            // 如果密码为空，提示用户输入
//            showPasswordInputDialog();
//        }
//        return password;
//    }
//
//    // 显示密码输入对话框(udp广播)
//    private void showPasswordInputDialog() {
//        new AlertDialog.Builder(this)
//                .setTitle("输入 WiFi 密码")
//                .setMessage("请输入当前 WiFi 的密码")
//                .setView(new EditText(this)) // 添加输入框
//                .setPositiveButton("确定", (dialog, which) -> {
//                    EditText input = ((AlertDialog) dialog).findViewById(android.R.id.edit);
//                    if (input != null) {
//                        String password = input.getText().toString();
//                        String ssid = getCurrentWifiSsid();
//                        // 保存密码到 SharedPreferences
//                        SharedPreferences sharedPreferences = getSharedPreferences("WifiPrefs", Context.MODE_PRIVATE);
//                        sharedPreferences.edit().putString("wifi_password", password).apply();
//                        // 重新尝试广播 WiFi 信息
//                        broadcastWifiInfo(ssid, password);
//                    }
//                })
//                .setNegativeButton("取消", null)
//                .show();
//    }
//
//    // 广播 WiFi 信息  (改用esptorch库）
//    private void broadcastWifiInfo(String ssid, String password) {
//        if (!ssid.isEmpty() && !password.isEmpty()) {
//            new Thread(() -> {
//                try {
//                    // 将 SSID 和密码打包成特定格式的数据
//                    String data = "WIFI:S:" + ssid + ";T:WPA;P:" + password + ";;";
//                    byte[] sendData = data.getBytes();
//
//                    // 创建 UDP 套接字
//                    DatagramSocket socket = new DatagramSocket();
//                    socket.setBroadcast(true);
//
//                    // 设置广播地址
//                    InetAddress broadcastAddress = InetAddress.getByName("255.255.255.255");
//                    DatagramPacket packet = new DatagramPacket(sendData, sendData.length, broadcastAddress, 8888);
//                    socket.send(packet);
//                    socket.close();
//
//                    // 提示用户
//                    runOnUiThread(() -> {
//                        Toast.makeText(RegisterActivity.this, "WiFi 信息已广播", Toast.LENGTH_SHORT).show();
//                    });
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    runOnUiThread(() -> {
//                        Toast.makeText(RegisterActivity.this, "广播失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
//                    });
//                }
//            }).start();
//        } else {
//            runOnUiThread(() -> {
//                Toast.makeText(RegisterActivity.this, "无法获取 WiFi 信息", Toast.LENGTH_SHORT).show();
//            });
//        }
//    }

}